<template>
    <div>
        <van-nav-bar title="注册" left-text="返回" left-arrow @click-left="onClickLeft" />
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="username" name="username" label="用户名" placeholder="用户名"
                    :rules="[{ pattern, message: '请填手机号' }]" />
                <van-field v-model="password" :type="status ? 'password' : 'input'" name="password" label="密码"
                    placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]">
                    <template #button>
                        <van-icon name="eye-o" @click="status = !status" />
                    </template>
                </van-field>
                <van-field v-model="yzm" type="input" name="input" label="验证码" placeholder="验证码"
                    :rules="[{ required: true, message: '请填验证码' }]" />
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    提交
                </van-button>
            </div>
            <div style="margin: 16px;">
                <van-button round block type="primary" class="hqyz" @click="hqyz">
                    获取验证码
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script setup>
import { registerApi } from '@/api/api'
import { ref } from 'vue'
import { showSuccessToast, showFailToast } from 'vant';
import router from '@/router';
let status = ref(true)

const onClickLeft = () => {
    router.push('/')
}
const username = ref('')
const password = ref('')
const pattern = /^1[3-9]\d{9}/
let timer = ref('')
const yzm = ref('')
let time = ref(5)
const hqyz = () => {
    yzm.value = Math.floor(Math.random() * 100000)
    timer = setInterval(() => {

        let yzmm = document.querySelector('.hqyz')
        time.value--;
        yzmm.innerHTML = time.value + '秒'
        if (time.value == 0) {
            clearInterval(timer)
            yzmm.innerHTML = '请重新获取'
            time.value = 5
        }
    }, 1000)
}
const onSubmit = () => {
    registerApi(username.value, password.value).then(res => {
        console.log(res);
        
        if (res.data.code == 0) {
            showSuccessToast('注册成功');
            router.push('/login')
        }
        else {
            showFailToast('注册失败');
        }
    })
}
</script>

<style lang="scss" scoped></style>